package com.iha.pongzor.logic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.iha.pongzor.data.HighScore;

public class AppHelper {

	public static List<HighScore> fetchHighscore() {
		List<HighScore> listItems = new ArrayList<HighScore>();

		try {
			URL URL = new URL("http://madfox.dk/smap/highscore.json.php");
			URLConnection con = URL.openConnection();

			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1"));

			StringBuilder SB = new StringBuilder();
			String line;
			while ((line = in.readLine()) != null) {
				SB.append(line);
			}
			JSONArray ja = new JSONArray(SB.toString());

			for (int i = 0; i < ja.length(); i++) {
				JSONObject jo = (JSONObject) ja.get(i);
				listItems.add(new HighScore(jo.getString("name"), jo.getInt("score"), jo.getInt("duration"), jo.getString("date")));
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return listItems;
	}
	
	public static void sendHighscore(HighScore highscore) {

		try {
			String Url = "http://madfox.dk/smap/highscore.json.php?name="+highscore.getName()+"&score="+highscore.getScore()+"&duration="+highscore.getSeconds()+"&date="+highscore.getDate();
//			URL URL = new URL(Url);
//			URL.openConnection();
			HttpClient httpC = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(Url);			
			httpC.execute(httpget);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
